public class java0708<K, V> {
    private static final int DEFAULT_CAPACITY = 16;
    private Entry<K, V>[] table;
    private int size;

    // 内部Entry类，用于存储键值对
    private static class Entry<K, V> {
        K key;
        V value;
        Entry<K, V> next;

        Entry(K key, V value, Entry<K, V> next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    public java0708() {
        this(DEFAULT_CAPACITY);
    }

    @SuppressWarnings("unchecked")
    public java0708(int capacity) {
        table = (Entry<K, V>[]) new Entry[capacity];
        size = 0;
    }

    // 简单的哈希函数
    private int hash(K key) {
        return (key == null) ? 0 : Math.abs(key.hashCode() % table.length);
    }

    // 添加键值对
    public void put(K key, V value) {
        int index = hash(key);
        Entry<K, V> entry = table[index];

        // 检查是否已存在相同的key
        while (entry != null) {
            if ((key == null && entry.key == null) ||
                    (key != null && key.equals(entry.key))) {
                entry.value = value; // 更新值
                return;
            }
            entry = entry.next;
        }

        // 添加新entry到链表头部
        table[index] = new Entry<>(key, value, table[index]);
        size++;
    }

    // 获取值
    public V get(K key) {
        int index = hash(key);
        Entry<K, V> entry = table[index];

        while (entry != null) {
            if ((key == null && entry.key == null) ||
                    (key != null && key.equals(entry.key))) {
                return entry.value;
            }
            entry = entry.next;
        }

        return null; // 未找到
    }

    // 删除键值对
    public void remove(K key) {
        int index = hash(key);
        Entry<K, V> prev = null;
        Entry<K, V> entry = table[index];

        while (entry != null) {
            if ((key == null && entry.key == null) ||
                    (key != null && key.equals(entry.key))) {
                if (prev == null) {
                    table[index] = entry.next; // 删除链表头节点
                } else {
                    prev.next = entry.next; // 删除中间节点
                }
                size--;
                return;
            }
            prev = entry;
            entry = entry.next;
        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }    public static void main(String[] args) {
        System.out.println("0708");
//        java0708<String, Integer> hashTable = new java0708<>();
//
//        hashTable.put("one", 1);
//        hashTable.put("two", 2);
//        hashTable.put("three", 3);
//
//        System.out.println(hashTable.get("two")); // 输出: 2
//
//        hashTable.remove("two");
//        System.out.println(hashTable.get("two")); // 输出: null
//
//        System.out.println("Size: " + hashTable.size()); // 输出: Size: 2

    }
}


